import { defineStore } from "pinia";
import { getToken, removeToken, setToken } from "../utils/token-utils";
import type { UserInfoState } from "./interface";
import { ElMessage } from "element-plus";
import { staticRoutes } from "@/router/routes";
import { cloneDeep } from "lodash";

import { reqLogin, reqUserInfo, reqLogout } from "@/api/login/index"; // 请求函数
import { allAsyncRoutes, anyRoute } from "@/router/routes";
import router from "@/router";

// 权限管理的实现
const permission = (asyncRoutes, routes) => {
  return asyncRoutes.filter((item) => {
    if ((routes || {}).includes(item.name)) {
      if (item.children && item.children.length > 0) {
        item.children = permission(item.children, routes);
      }
      return true;
    }
  });
};

/**
 * 用户信息
 * @methods setUserInfos 设置用户信息
 */
export const useUserInfoStore = defineStore("userInfo", {
  state: (): UserInfoState => ({
    token: getToken() as string, // token
    name: "", // 用户名
    avatar: "", // 用户头像
    menuRoutes: [], // tab菜单展示的数据
    buttons: [], // 按钮的数据
  }),

  actions: {
    // 登录
    async login(username: string, password: string) {
      try {
        let result = await reqLogin({ username, password });
        this.token = result.token;
        setToken(result.token);
        return "ok";
      } catch (error) {
        ElMessage.error("用户名或密码错误");
        return Promise.reject(new Error(error.message));
      }
    },

    // 获取用户信息
    async getInfo() {
      try {
        let result = await reqUserInfo();
        this.name = result.name;
        this.avatar = result.avatar;
        this.buttons = result.buttons;
        const newAllAsyncRoutes = permission(
          cloneDeep(allAsyncRoutes),
          result.routes
        );
        const asyncRoutes = [...newAllAsyncRoutes, anyRoute];
        asyncRoutes.forEach((item) => {
          router.addRoute(item);
        });
        this.menuRoutes = [...staticRoutes, ...newAllAsyncRoutes];

        return "ok";
      } catch (error) {
        return Promise.reject(new Error(error.message));
      }
    },

    // 退出登录
    async reset() {
      try {
        await reqLogout();
        removeToken();
        this.token = "";
        this.name = "";
        this.avatar = "";
        router.getRoutes().forEach((item) => {
          router.removeRoute(item.name);
        });
        staticRoutes.forEach((item) => {
          router.addRoute(item);
        });

        return "ok";
      } catch (error) {
        return Promise.reject(new Error(error.message));
      }
    },
  },
});
